package com.lcb.jmm.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/****
 * @Author:刘长柏
 * @Date: 2021-01-05 10:48
 * @Description: 原子类ABA问题
 *****/
public class AtomicAbaProblemTest {

    static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) {

        Thread main = new Thread(new Runnable() {
            public void run() {
                System.out.println("操作线程:" + Thread.currentThread().getName() + "--修改前操作数值:" + atomicInteger.get());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println( atomicInteger.get());

                boolean isCasSuccess = atomicInteger.compareAndSet(1, 2);

                System.out.println(isCasSuccess);

                System.out.println("操作线程:" + Thread.currentThread().getName() + "--修改后操作数值:" + atomicInteger.get());
            }
        }, "主线程");

        Thread other = new Thread(new Runnable() {
            public void run() {
                atomicInteger.incrementAndGet();
                System.out.println("操作线程:" + Thread.currentThread().getName() + "--自加操作后:" + atomicInteger.get());
                atomicInteger.decrementAndGet();
                System.out.println("操作线程:" + Thread.currentThread().getName() + "--自减操作后:" + atomicInteger.get());
            }
        }, "干扰线程");

        main.start();
        other.start();
    }
}
